#include "myinet.h"
#include "tools.h"
#include <time.h>

/*** 访问日期服务的客户端 ***/

/**
 * @return 0表示成功，否则失败
 * @param buf 用于存放时间的缓冲区
 */
int 
main(int argc, char** argv){
    if (argc < 3){
        fprintf(stderr, "usage: %s <addr> <port>\n", argv[0]);
        error_exit(NULL, "error parsing options");
    }

    int sfd;
    struct sockaddr_in addr;
    char buf[1024] = {0};

    // 创建套接字
    if ((sfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0){
        error_exit("socket", NULL);
    }

    // get host
    struct hostent* host_entity = 
        gethostbyname(argv[1]);
    info(argv[1]);

    if (host_entity == NULL || (host_entity->h_addr == NULL)){
        error_exit("gethostbyname", "Error: Wrong host address");
    }

    addr.sin_addr = *(struct in_addr*)(host_entity->h_addr);
    addr.sin_family = AF_INET;

    addr.sin_port = htons(atoi(argv[2]));

    int slen = sizeof(addr);

    // 发送请求
    if (sendto(sfd, "a", 1, 0, (struct sockaddr*)&addr, sizeof(addr)) < 0){
        error_exit("sendto", NULL);
    }

    int received_len = 0;

    // 等待回应
    if ((received_len = recvfrom(sfd, buf, sizeof(buf), 0, (struct sockaddr*)&addr, &slen)) < 0){
        error_exit("recvfrom", NULL);
    }

    time_t rec_time = *(unsigned long*)&buf;

    // 输出格式化的日期
    // yyyy/MM/dd hh:mm:ss
    struct tm* t = localtime(&rec_time);

    printf("received time: %d/%d/%d %02d:%02d:%02d\n", 
            t->tm_year + 1900,
            t->tm_mon + 1,
            t->tm_mday,
            t->tm_hour,
            t->tm_min,
            t->tm_sec);
    
    return 0;
}
